import { Component } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { GridOptions } from '@ag-grid-community/core';
import { RenderOperatingButtonComponent } from '@shared/ag-grid-ext/cell-renders/render-operating-button.component';
import { GridConfigService } from '@core/config/grid-config.service';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { map, mergeMap } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { deepClone, getJson, missing } from '../../../utils/utils';
import { ApiService } from '@core/services/http/api.service';
import { SubjectService } from '@core/services/events/subject.service';
import { FormService } from '@core/services/form.service';
import { FormGroup } from '@angular/forms';
import { FormlyFormOptions } from '@ngx-formly/core';


@Component({
  selector: 'apes-render-xml-detail',
  template: `
    <div class="apes-xml-detail" [ngStyle]="{height:_height}">
      <apes-spin *ngIf="isLoading"
                 apesSimple
                 apesTip="加载中..."
                 class="apes-xml-detail-spin"></apes-spin>
      <div class="apes-xml-detail-box">
        <form apes-form>
          <ng-container *ngFor="let datas of formMetadata">
            <apes-box [data]="datas" [model]="model" [form]="form" [options]="options"></apes-box>
          </ng-container>
        </form>
      </div>
    </div>
  `,
  styles: [`
    .apes-xml-detail {
      overflow: hidden;
      background: #e6f3f3;
    }

    .apes-xml-detail-box {
      height: calc(100% - 8px);
      overflow: auto;
    }

    .apes-xml-detail-spin {
      position: absolute;
      z-index: 1000;
      width: 100%;
      height: 100%;
      background: rgba(187, 187, 187, 0.47);
    }

    .apes-xml-detail /deep/ .apes-spin {
      position: absolute;
      left: 50%;
      top: 50%;
    }

  `],
})
export class RenderXmlDetailComponent implements ICellRendererAngularComp {
  refresh(params: any): boolean {
    return false;
  }

  params: any;

  _height: any;
  masterGridData: any;
  isLoading: boolean = true;

  form: FormGroup;
  formMetadata = [];
  ctx: any = {};
  tableValid = {};
  model: any = {};
  subjects = {};
  options: FormlyFormOptions = {};
  api: any;
  formId: any;

  constructor(
    protected apiService: ApiService,
    private formService: FormService,
    protected subject: SubjectService,
    protected expressionService: ExpressionService,
  ) {
  }

  agInit(params: any): void {
    this.form = new FormGroup({});
    this.params = params;
    // if (params.context) {
    //   this.ctx = params.context;
    // }

    this._height = params.detailRowHeight ? params.detailRowHeight + 'px' : '300px';
    this.masterGridData = params.data;
    this.initContext(params);
    this.initDetailData(params);
  }

  initDetailData(params) {
    let options = params.detailGridOptions.options;
    this.formId = options.formId;
    this.api = options.api;
    this.getFormMetadata(this.formId);
  }

  private initContext(params) {
    // this.clearValue(this.model);
    this.form.reset({});
    // this.clearValue(this.ctx);
    // this.ctx.user = this.user;
    this.ctx.model = this.model;
    // this.setStates('new');
    this.ctx.form = this.form;
    this.ctx.subjects = this.subjects;
    // this.clearValue(this.tableValid);
    // this.ctx.valid = true;
    this.ctx.states = 'new';
    this.options.formState = this.ctx;
    if (params.context) {
      this.ctx.primaryCtx = params.context;
    }
    // this.ctx.searchService = this.searchService;
    // // 动态表单配置
    if (this.formMetadata && this.formMetadata.length > 0) {
      this.ctx.$formMetadata = this.formMetadata;
    }
  }

  /**
   * 功能：获取表单元数据
   */
  private getFormMetadata(formId) {
    this.getFormMetadataApi(formId).pipe(
      map((body) => {
        return body;
      }),
    ).subscribe((body) => {
      let metadata = body.sheet;
      this.formService.extFormMetadata(metadata, this.ctx, this.subject, this.tableValid);
      this.formMetadata = this.formMetadata.concat(metadata);

      this.ctx.$formMetadata = this.formMetadata;

      if (body.global) {
        this.interceptEventListener(body.global.events);
        // if (body.global.api) this.api = body.global.api;
      }

      // this.subject.publish(this.ctx, this.subject.event_form_refresh, this.ctx);


      this.getDetailData();
    });
  }

  private getFormMetadataApi(formId: string): Observable<any> {
    return this.apiService.post('form.get', { 'body': getJson({ id: formId }) }).pipe(map(
      (body) => {
        if (body) {
          return body;
        }
      }));
  }

  private getDetailData() {
    let api = this.api;
    let setData = this.masterGridData;
    this.apiService.post(api, setData).subscribe((body) => {
      console.log('数据--', body);
      if (body) {
        this.refreshData(body);
      }
      this.isLoading = false;
    });
  }

  /**
   * 功能：注册事件监听器
   * @param {string} topic
   */
  interceptEventListener(events: any[]) {
    if (missing(events)) return;
    events.forEach(em => {
      em.type.split(',').forEach(type => {
        /**订阅事件**/
        this.subject.subscribe(this.ctx, type, data => {
          this.expressionService.evaluate(em.callback, {
            context: this.ctx,
            form: this.form,
            model: this.model,
            data: data,
          }, true);
        });
      });
    });
  }

  private clearValue(object: any) {
    for (let key in object) {
      if (key.startsWith('grid_')) continue;
      delete object[key];
    }
  }

  private refreshData(data) {
    this.ctx.states = 'new';
    this.clearValue(this.model);
    for (let key in data) {
      this.model[key] = data[key];
      if (key == 'id') {
        this.ctx[key] = data[key];
      }
    }
    this.form.reset(data);
    this.subject.publish(this.ctx, this.subject.event_form_refresh, data);
  }
}
